package com.fuqi.framework.network.api;

import android.util.Log;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.RetryPolicy;
import com.android.volley.error.AuthFailureError;
import com.android.volley.error.NoConnectionError;
import com.android.volley.error.ParseError;
import com.android.volley.error.ServerError;
import com.android.volley.error.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.fuqi.android.zhongcai.application.UniApplication;
import com.fuqi.android.zhongcai.utils.ActivityUtils;
import com.fuqi.android.zhongcai.utils.LogUtils;
import com.fuqi.framework.exception.HeaderCodeError;
import com.fuqi.framework.gson.GsonHelper;
import com.fuqi.framework.network.code.HandleCode;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public abstract class AbsRequest<PARAMS extends Map<String, String>, RESULT> extends Request<RESULT> {

    private Class<RESULT> mClass;
    private Listener<RESULT> mListener;
    public static final int MY_SOCKET_TIMEOUT_MS = 10000;
    private Map<String, String> mParamsMap;
    private String url;
    public AbsRequest(int method, String url, PARAMS params,
                      Listener<RESULT> listener, ErrorListener errorListener, Class<RESULT> clazz) {
        super(Method.POST, url, errorListener);
        LogUtils.i("juner request url: " + url + " request params: " + GsonHelper.writeValue(params));
        mClass = clazz;
        mListener = listener;
        mParamsMap = params;
        this.url = url;
    }

    @Override
    public RetryPolicy getRetryPolicy() {
        return new DefaultRetryPolicy(MY_SOCKET_TIMEOUT_MS,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    }


    @Override
    protected void deliverResponse(RESULT response) {
        mListener.onResponse(response);
    }

    @Override
    public void deliverError(VolleyError error) {
        super.deliverError(error);
        if (error instanceof ParseError) {
            ActivityUtils.toast("解析错误!");
            LogUtils.i("deliverError 解析错误: " + url);
        } else if (error instanceof ServerError) {
            ActivityUtils.toast("服务器错误!");
        } else if (error instanceof NoConnectionError) {
            ActivityUtils.toast("服务器连接失败!");
        } else if (error instanceof HeaderCodeError) {
            if (((HeaderCodeError) error).getStatusCode() == 21013) {
                ActivityUtils.toast("请求错误!");
            } else {


            }
        }
        Log.e("juner", "juner: " + error.toString());
    }


    protected void parseHeaders(NetworkResponse response) throws HeaderCodeError, JSONException {
        Log.i("juner", "juner:" + response.headers.toString());
        int headerCode = Integer.parseInt(response.headers.get("HTTP_HEADER_CODE").toString());
        String headerMessage = response.headers.get("HTTP_HEADER_MSG");
        if (!headerMessage.equals(""))
            headerMessage = new JSONTokener(headerMessage).nextValue().toString();
        if (headerCode != 200) {
            throw new HeaderCodeError(headerCode, headerMessage);
        }
    }

    protected RESULT parseData(NetworkResponse response) throws UnsupportedEncodingException, JSONException {
        String jsonString = new String(response.data,
                HttpHeaderParser.parseCharset(response.headers));
        JSONObject jo;
        Log.i("juner", "juner NetworkResponse:" + jsonString);
        jo = new JSONObject(jsonString.toString());
        HandleCode.code = Integer.valueOf(jo.getString("status"));
        HandleCode.headerMessage = String.valueOf(jo.getString("msg"));
        return GsonHelper.getDeserializer().fromJson(jo.getString("data"), mClass);
    }

    @Override
    protected Response<RESULT> parseNetworkResponse(NetworkResponse response) {
        try {

            //parseHeaders(response);//解析头部
            RESULT result = parseData(response);//解析body

            return Response.success(
                    result,
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException e) {
            return Response.error(new ParseError(e));
        } /*catch (HeaderCodeError e) {
            return Response.error(e);
		} */
    }

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        return mParamsMap;
    }



	@Override
	public Map<String, String> getHeaders() throws AuthFailureError {
		HashMap<String, String> headers = new HashMap<String, String>();
        if (UniApplication.getInstance().hasLogin()) {
            headers.put("TOKEN", UniApplication.getInstance().getUserInfo().getToken());
        }
        Log.i("juner", "juner headers:"+headers.toString());
		return headers;
	}

}
